
#include "my_net.h"
#include <netdb.h>
#include <strings.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>

sockfd TcpConnect(const char *host, const char *port) {

    struct addrinfo hints;
    struct addrinfo * result;

    bzero(&hints, sizeof(hints));

    hints.ai_socktype = SOCK_STREAM;
    hints.ai_family   = AF_UNSPEC;

    int rt = getaddrinfo(host, port, &hints, &result);

    if (rt == 0) {

        sockfd fd = -1;
        struct addrinfo * ptr = result;
        while (ptr) {

            fd = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
            if (fd < 0) {

                continue;
            }
            if (connect(fd, ptr->ai_addr, ptr->ai_addrlen) == 0) {

                return fd;
            }
            ptr = ptr->ai_next;
        }
    }
    return -1;
}
